package com.gensdai.leliang.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gensdai.leliang.R;
import com.gensdai.leliang.activity.OrderPreper2Activity;
import com.gensdai.leliang.activity.OrderPreper3Activity;
import com.gensdai.leliang.activity.OrderPreperActivity;
import com.gensdai.leliang.activity.ProductDetail;
import com.gensdai.leliang.activity.UserNews;
import com.gensdai.leliang.adapter.cartcard_list_adapter;
import com.gensdai.leliang.base.BaseFragment;
import com.gensdai.leliang.common.clickinterface.MenuItemChangeListener;
import com.gensdai.leliang.dialog.Upload;
import com.gensdai.leliang.entity.CardCart;
import com.gensdai.leliang.entity.parseBean.OrderPreperBean;
import com.gensdai.leliang.entity.parseBean.ProductAttributesListBean;
import com.gensdai.leliang.entity.parseBean.ProductInfo;
import com.gensdai.leliang.json_base.json_base;
import com.gensdai.leliang.remoteInterface.ApiService;
import com.gensdai.leliang.remoteInterface.URLConfig;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 首页购物车fragment
 * Created by liutao on 2017/5/23.
 */

public class FragmentCartCard extends BaseFragment implements AdapterView.OnItemClickListener, View.OnClickListener {

    @BindView(R.id.cartcard_list)
    ListView cartcardList;
    Unbinder unbinder; //list
    @BindView(R.id.check_all)
    LinearLayout checkAll;//全选按钮
    @BindView(R.id.click_all)
    ImageView clickAll;//按钮图片
    @BindView(R.id.user_news)
    ImageView userNews;//消息按钮图片
    @BindView(R.id.all_money)
    TextView allMoney;//总价
    @BindView(R.id.go_shop)
    TextView go_shop;//去逛逛
    @BindView(R.id.go_clearing)
    TextView go_clearing;//去结算
    @BindView(R.id.no_data)
    LinearLayout noData; //无数据界面
    @BindView(R.id.clearing)
    RelativeLayout clearing; //下面的结算布局
    @BindView(R.id.delete_cartcard)
    ImageView delete_cartcard; //最上角删除按钮
    @BindView(R.id.go_back)
    ImageView go_back; //返回
    @BindView(R.id.geshu)
    TextView geshu; //个数

    private cartcard_list_adapter list_adapter;
    private List<CardCart> list_data = null;
    private CardCart cart = null;
    private Upload up;

    public double all_money = 0;//总价格
    private final int APPEND = 1;//钱加
    private final int SUBTRACT = 2;//钱减
    private final int GESHUJIA = 3;//个数加
    private final int GESHUJIAN = 4;//个数减
    private final int ENTER = 5; // 查询
    private final int DELETE = 6; // 删除
    private final int UPDATA = 7; // 编辑

    private boolean click_all = false;// 全选状态
    private boolean delete_or_add = false; // false 减少 true为增加

    private Handler mhandler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case APPEND:
                    all_money += (double) msg.obj;
                    allMoney.setText(getString(R.string.all_money) + zhuanhua(all_money));
                    break;
                case SUBTRACT:
                    all_money -= (double) msg.obj;
                    allMoney.setText(getString(R.string.all_money) + zhuanhua(all_money));
                    break;
                case GESHUJIA:
                    list_data.get((int) msg.obj).setNumber(Integer.parseInt(list_data.get((int) msg.obj).getNumber()) + 1 + "");
                    if (list_data.get((int) msg.obj).getSelect_state().equals("0")) {
                        all_money += Double.parseDouble(
                                list_data.get((Integer) msg.obj).getPrice());
                        allMoney.setText(
                                getString(R.string.all_money) + zhuanhua(all_money)
//                                        (Double.parseDouble(list_data.get((Integer) msg.obj).getNumber())
//                                                * Double.parseDouble(list_data.get((Integer) msg.obj).getPrice())
//                                        )
                        );

                    }

                    break;
                case GESHUJIAN:
                    list_data.get((int) msg.obj).setNumber(Integer.parseInt(list_data.get((int) msg.obj).getNumber()) - 1 + "");
                    if (list_data.get((int) msg.obj).getSelect_state().equals("0")) {
                        all_money -= Double.parseDouble(
                                list_data.get((Integer) msg.obj).getPrice());
                        allMoney.setText(
                                getString(R.string.all_money) + zhuanhua(all_money)
//                                        (Double.parseDouble(list_data.get((Integer) msg.obj).getNumber())
//                                                * Double.parseDouble(list_data.get((Integer) msg.obj).getPrice())
//                                        )
                        );
                    }
                    break;
                case ENTER:
                    up.dismiss();
                    try {
                        if (new json_base().GOOD((String) msg.obj)) {
                            if (list_data != null) {
                                list_data.clear();
                            }
                            list_data = (List<CardCart>) new json_base().jsonCartCard(new JSONObject((String) msg.obj));
                            setmlist();
                            CountMoney();
                        } else {
                            Toast.makeText(
                                    getActivity(),
                                    new JSONObject((String) msg.obj)
                                            .getString("message"),
                                    Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                case DELETE:
                    up.dismiss();
                    try {
                        if (new json_base().GOOD((String) msg.obj)) {
                            all_money = 0;
                            allMoney.setText(getString(R.string.all_money) + zhuanhua(all_money));
                            setmlist();
                        } else {

                        }
                        Toast.makeText(
                                getActivity(),
                                new JSONObject((String) msg.obj)
                                        .getString("message"),
                                Toast.LENGTH_SHORT).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                case UPDATA:
                    up.dismiss();
                    try {
                        if (new json_base().GOOD((String) msg.obj)) {
                            if (delete_or_add) {
                                Message m = new Message();
                                m.obj = msg.arg1;
                                m.what = GESHUJIA;
                                mhandler.sendMessage(m);
                            } else {
                                Message m = new Message();
                                m.obj = msg.arg1;
                                m.what = GESHUJIAN;
                                mhandler.sendMessage(m);
                            }
                        } else {
                        }
                        Toast.makeText(
                                getActivity(),
                                new JSONObject((String) msg.obj)
                                        .getString("message"),
                                Toast.LENGTH_SHORT).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                default:
                    up.dismiss();
                    break;
            }
        }
    };


    int flag = -1;

    public static FragmentCartCard NewInstance(int flag) {
        FragmentCartCard cartCard = new FragmentCartCard();
        Bundle bundle = new Bundle();
        bundle.putInt("flag", flag);
        cartCard.setArguments(bundle);
        return cartCard;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            flag = getArguments().getInt("flag", -1);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_cartcard, container, false);
        unbinder = ButterKnife.bind(this, v);
        init();
//        setmlist();
//        SelectShopCarRequestStr();
        return v;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        all_money = 0;
        allMoney.setText(getString(R.string.all_money) + all_money);
        clickAll.setBackground(ContextCompat.getDrawable(getActivity(), R.mipmap.xuanyuan));
        this.click_all = false;

    }

    @Override
    public void onStart() {
        super.onStart();
        Query();
        all_money = 0;
        String s = getActivity().getSharedPreferences("User", getActivity().MODE_PRIVATE).getString("newsCall", "0");
        if (Integer.parseInt(s) > 0) {
            geshu.setText(s);
            geshu.setVisibility(View.VISIBLE);
        }
        SelectShopCarRequestStr();

    }

    private void setmlist() {

        if (list_data.size() > 0) {
            list_adapter = new cartcard_list_adapter(getActivity(), list_data, mhandler, click);
            cartcardList.setAdapter(list_adapter);

            allMoney.setText(getString(R.string.all_money) + zhuanhua(all_money));
            cartcardList.setVisibility(View.VISIBLE);
            clearing.setVisibility(View.VISIBLE);
            delete_cartcard.setVisibility(View.VISIBLE);
            noData.setVisibility(View.GONE);
        } else {
            cartcardList.setVisibility(View.GONE);
            clearing.setVisibility(View.GONE);
            all_money = 0;
            allMoney.setText(getString(R.string.all_money) + all_money);
            noData.setVisibility(View.VISIBLE);
        }

    }

    private void UpdatamList() {
        if (list_data != null || list_data.size() > 0) {
            list_adapter.notifyDataSetChanged();
            cartcardList.setVisibility(View.VISIBLE);
            clearing.setVisibility(View.VISIBLE);
            noData.setVisibility(View.GONE);
        } else {
            cartcardList.setVisibility(View.GONE);
            all_money = 0;
            allMoney.setText(getString(R.string.all_money) + all_money);
            clearing.setVisibility(View.GONE);
            noData.setVisibility(View.VISIBLE);
        }

    }

    /**
     * 初始化
     */
    private void init() {
        up = new Upload(getActivity());
        list_data = new ArrayList<CardCart>();

        delete_cartcard.setOnClickListener(this);
        go_clearing.setOnClickListener(this);
        go_shop.setOnClickListener(this);
        checkAll.setOnClickListener(this);
        go_back.setOnClickListener(this);
        userNews.setOnClickListener(this);

        if (flag != -1) {
            go_back.setVisibility(View.VISIBLE);
            go_shop.setVisibility(View.GONE);
        } else {
            go_back.setVisibility(View.GONE);
            go_shop.setVisibility(View.VISIBLE);
        }

        cartcardList.setOnItemClickListener(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
        if (list_data.get(position).getShopCarState().equals("1")) {
            ImageView cartcatdItmeCb = (ImageView) view.findViewById(R.id.cartcatd_itme_cb);
            if (list_data.get(position).getSelect_state().equals("1")) {
                cartcatdItmeCb.setBackground(ContextCompat.getDrawable(getActivity(), R.mipmap.xuanyuan));
                sendmsg(APPEND, Double.parseDouble(
                        list_data.get(position).getPrice())
                        * Double.parseDouble(list_data.get(position).getNumber())); // 加上选中的
                list_data.get(position).setSelect_state("0"); //0 选中
                delete_cartcard.setVisibility(View.VISIBLE);
            } else {
                cartcatdItmeCb.setBackground(ContextCompat.getDrawable(getActivity(), R.mipmap.yuan));
                sendmsg(SUBTRACT, Double.parseDouble(
                        list_data.get(position).getPrice())
                        * Double.parseDouble(list_data.get(position).getNumber())); // 减去取消选择的
                list_data.get(position).setSelect_state("1"); // 1 为选择
                clickAll.setBackground(ContextCompat.getDrawable(getActivity(), R.mipmap.yuan));
                this.click_all = true;
            }
        } else {

        }
    }

    /**
     * 回调
     *
     * @param flag
     */
    private void sendmsg(int flag, Double money) {
        Message msg = new Message();
        msg.what = flag;
        msg.obj = money;
        mhandler.sendMessage(msg);
    }

    /**
     * 回调
     *
     * @param flag
     */
    private void sendmsg(int flag, int money) {
        Message msg = new Message();
        msg.what = flag;
        msg.obj = money;
        mhandler.sendMessage(msg);
    }

    /**
     * 计算价格
     */
    private void CountMoney() {
        if (list_data == null || list_data.size() == 0) {
            return;
        }
        for (int i = 0; i < list_data.size(); i++) {
            if (list_data.get(i).getShopCarState().equals("1")) {
                list_data.get(i).setSelect_state("0");
                sendmsg(APPEND, Double.parseDouble(
                        list_data.get(i).getPrice())
                        * Double.parseDouble(list_data.get(i).getNumber()));
            }
        }
    }

    /**
     * 设置状态
     *
     * @param click_all
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void setState(boolean click_all) {

        if (click_all) {
            this.click_all = false;
            all_money = 0;
            for (int i = 0; i < list_data.size(); i++) {
                if (list_data.get(i).getShopCarState().equals("1")) {
                    list_data.get(i).setSelect_state("0");
                    sendmsg(APPEND, Double.parseDouble(
                            list_data.get(i).getPrice())
                            * Double.parseDouble(list_data.get(i).getNumber()));
                }
            }
            clickAll.setBackground(ContextCompat.getDrawable(getActivity(), R.mipmap.xuanyuan));
            delete_cartcard.setVisibility(View.VISIBLE);
        } else {
            this.click_all = true;
            for (int i = 0; i < list_data.size(); i++) {
                if (list_data.get(i).getShopCarState().equals("1")) {
                    list_data.get(i).setSelect_state("1");
                    sendmsg(SUBTRACT, Double.parseDouble(
                            list_data.get(i).getPrice())
                            * Double.parseDouble(list_data.get(i).getNumber()));
                }
            }
            clickAll.setBackground(ContextCompat.getDrawable(getActivity(), R.mipmap.yuan));
            delete_cartcard.setVisibility(View.GONE);
        }
    }

    /**
     * 回调函数
     */
    cartcard_list_adapter.onjiajianClick click = new cartcard_list_adapter.onjiajianClick() {
        @Override
        public void jia(int position, CardCart cardCart) {
            delete_or_add = true;
            UpdateShopCarRequestStr(list_data.get(position).getId(), "add", position);
//            sendmsg(3, position);
        }

        @Override
        public void jian(int position, CardCart cardCart) {

            delete_or_add = false;
            UpdateShopCarRequestStr(list_data.get(position).getId(), "reduce", position);
//            sendPosintion(4, position);
        }

        @Override
        public void tu(int position) {
            Intent intent = new Intent(getActivity(), ProductDetail.class);
            intent.putExtra(ProductDetail.EXTRA_PID, list_data.get(position).getProductId());
            getActivity().startActivity(intent);
        }
    };

    /**
     * 回调，判断list显示是增加还是减少
     *
     * @param flag
     * @param position
     */
    private void sendPosintion(int flag, int position) {
        sendmsg(flag, position);
    }


    /**
     * 查看购物车----------------------------------------------------------------------
     */
    private void SelectShopCarRequestStr() {
        //获取edit的值后请求


        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("token", getActivity().getSharedPreferences("User", getActivity().MODE_PRIVATE).getString("token", ""));   //用户id
        loginParams.put("userno", getActivity().getSharedPreferences("User", getActivity().MODE_PRIVATE).getString("userno", ""));   //用户no

//        Log.e("New_delivery_address", loginParams.get("detailedAddress"));
        toStr(loginParams);
    }

    //返回字符串类型
    private void toStr(Map<String, String> loginParams) {
        up.show();
        ApiService.getInstance(getActivity()).SelectShopCarRequestStr(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                               @Override
                               public void onSubscribe(@NonNull Disposable d) {
                                   //可以取消订阅
                                   //还可以判断是否处于取消状态
                                   //boolean b=d.isDisposed();

                                   Log.d("onSubscribe", "onSubscribe");
                               }

                               @Override
                               public void onNext(@NonNull String s) {
                                   //处理得到的数据
                                   Message msg = new Message();
                                   msg.what = ENTER;
                                   msg.obj = s;
                                   mhandler.sendMessage(msg);
                               }

                               @Override
                               public void onError(@NonNull Throwable e) {
                                   //异常处理
                                   up.dismiss();
                               }

                               @Override
                               public void onComplete() {
                                   //监听完毕后的处理
                                   Log.d("onComplete", "onComplete");
                               }
                           }
                );
    }


    /**
     * 删除购物车订单----------------------------------------------------------------------
     *
     * @param delete_data
     */
    private void DeleteShopCarRequestStr(StringBuffer delete_data, StringBuffer delete_id) {
        //获取edit的值后请求


        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("prodRelaId", delete_data.toString());   //订单id
        loginParams.put("token", getActivity().getSharedPreferences("User", getActivity().MODE_PRIVATE).getString("token", ""));   //用户id
        loginParams.put("prodAttrId", delete_id.toString());   //商品属性ID
        Log.e("prodRelaId", delete_data.toString());
        DeleteShopCarRequestStr(loginParams);
    }

    //返回字符串类型
    private void DeleteShopCarRequestStr(Map<String, String> loginParams) {
        up.show();
        ApiService.getInstance(getActivity()).DeleteShopCarRequestStr(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                               @Override
                               public void onSubscribe(@NonNull Disposable d) {
                                   //可以取消订阅
                                   //还可以判断是否处于取消状态
                                   //boolean b=d.isDisposed();

                                   Log.d("onSubscribe", "onSubscribe");
                               }

                               @Override
                               public void onNext(@NonNull String s) {
                                   //处理得到的数据
                                   Log.e("quick_login", s);
                                   Message msg = new Message();
                                   msg.what = DELETE;
                                   msg.obj = s;
                                   mhandler.sendMessage(msg);
                               }

                               @Override
                               public void onError(@NonNull Throwable e) {
                                   //异常处理
                                   up.dismiss();
                                   Log.e("onError", e.getMessage());
                               }

                               @Override
                               public void onComplete() {
                                   //监听完毕后的处理
                                   Log.d("onComplete", "onComplete");
                               }
                           }
                );
    }

    /**
     * 编辑购物车订单----------------------------------------------------------------------
     */
    private void UpdateShopCarRequestStr(String data, String tpye, int position) {
        //获取edit的值后请求


        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("shopCarId", data);   //订单id
        loginParams.put("type", tpye);   //增加删除
        loginParams.put("token", getActivity().getSharedPreferences("User", getActivity().MODE_PRIVATE).getString("token", ""));   //用户id
        Log.e("prodRelaId", data);
        UpdateShopCarRequestStr(loginParams, position);
    }

    //返回字符串类型
    private void UpdateShopCarRequestStr(Map<String, String> loginParams, final int position) {
        up.show();
        ApiService.getInstance(getActivity()).UpdateShopCarRequestStr(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                               @Override
                               public void onSubscribe(@NonNull Disposable d) {
                                   //可以取消订阅
                                   //还可以判断是否处于取消状态
                                   //boolean b=d.isDisposed();

                                   Log.d("onSubscribe", "onSubscribe");
                               }

                               @Override
                               public void onNext(@NonNull String s) {
                                   //处理得到的数据
                                   Log.e("quick_login", s);
                                   if (new json_base().GOOD((s))) {
                                       Message msg = new Message();
                                       msg.what = UPDATA;
                                       msg.obj = s;
                                       msg.arg1 = position;
                                       mhandler.sendMessage(msg);
                                   } else {
                                       up.dismiss();
                                       try {
                                           Toast.makeText(
                                                   getActivity(),
                                                   new JSONObject((s))
                                                           .getString("message"),
                                                   Toast.LENGTH_SHORT).show();
                                           list_adapter.notifyDataSetChanged();
                                       } catch (JSONException e) {
                                           e.printStackTrace();
                                       }
                                   }
                               }

                               @Override
                               public void onError(@NonNull Throwable e) {
                                   //异常处理
                                   up.dismiss();
                                   Log.e("onError", e.getMessage());
                               }

                               @Override
                               public void onComplete() {
                                   //监听完毕后的处理
                                   Log.d("onComplete", "onComplete");
                               }
                           }
                );
    }

    /**
     * 查询消息
     */
    private void Query() {
        //获取edit的值后请求

        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("userNo", getActivity().getSharedPreferences("User", getActivity().MODE_PRIVATE).getString("userno", ""));
        toStrNews(loginParams);
    }

    //返回字符串类型
    private void toStrNews(Map<String, String> loginParams) {
        ApiService.getInstance(getActivity()).CQUERY_MESSAGE_COUNT_Receipt(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(FragmentEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        try {
                            int i = 0;
                            if (new json_base().GOOD(s)) {
                                String[] list = (String[]) new json_base().JsonCall(new JSONObject(s));
                                i = Integer.parseInt(list[0]) + Integer.parseInt(list[1]);
                                if (i > 0) {
                                    if (i > 99) {
                                        geshu.setText("99+");
                                    } else {
                                        geshu.setText(i + "");
                                    }
                                    geshu.setVisibility(View.VISIBLE);
                                } else {
                                    geshu.setVisibility(View.INVISIBLE);
                                }
                            } else {
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }

    @Override
    public void onClick(View v) {
        StringBuffer delete_data = new StringBuffer();
        StringBuffer delete_id = new StringBuffer();
        switch (v.getId()) {
            case R.id.delete_cartcard:
                List<CardCart> list_datass = new ArrayList<CardCart>();
                for (int i = 0; i < list_data.size(); i++) {
                    if (list_data.get(i).getSelect_state().equals("0")) {
                        list_datass.add(list_data.get(i));
                    }
                }
                if (list_datass.size() < 1) {
                    Toast.makeText(getActivity(), "最少选择一个商品！", Toast.LENGTH_SHORT).show();
                    return;
                }
                for (int i = 0; i < list_data.size(); i++) {
                    if (list_data.get(i).getSelect_state().equals("0")) {
                        Log.e("list_data", list_data.size() + "");
                        delete_data.append(list_data.get(i).getProductId() + ",");
                        delete_id.append(list_data.get(i).getProductAttributeId() + ",");
                        list_data.remove(i);
                        i--;
                    }
                }
                UpdatamList();
                DeleteShopCarRequestStr(delete_data, delete_id);
                break;
            case R.id.go_clearing:
                List<CardCart> list_datas = new ArrayList<CardCart>();
                for (int i = 0; i < list_data.size(); i++) {
                    if (list_data.get(i).getSelect_state().equals("0") && list_data.get(i).getShopCarState().equals("1")) {
                        list_datas.add(list_data.get(i));
                    }
                }
                Log.e("list_datas:", list_datas.size() + "");
                if (list_datas.size() < 1) {
                    Toast.makeText(getActivity(), "最少选择一个商品！", Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent go_clearing = new Intent(getActivity(), OrderPreper3Activity.class);
                go_clearing.putExtra(OrderPreperActivity.EXTRA_PRODUCT, (Serializable) startSwitch(list_datas));
                go_clearing.putExtra(OrderPreperActivity.EXTRA_FROM_FLAG, "1");
                startActivity(go_clearing);
                break;
            case R.id.go_shop:
                if (menulistener != null) {
                    menulistener.changePosition(ContentTypeFragment.HOT_0);
                }
//                SelectShopCarRequestStr();
                break;
            case R.id.check_all: // 全选按钮
                setState(click_all);
                setmlist();
                UpdatamList();
                break;
            case R.id.go_back: //从商品详情进来
                getActivity().finish();
                break;
            case R.id.user_news: //消息中心
                getActivity().startActivity(new Intent(getActivity(), UserNews.class));
                break;
            default:
                break;
        }
    }

    /**
     * 转换对象
     *
     * @param list
     * @return
     */
    private List<OrderPreperBean> startSwitch(List<CardCart> list) {
        List<OrderPreperBean> orderList = new ArrayList<>();
        OrderPreperBean orderPreperBean;
        ProductInfo productInfo;
        ProductAttributesListBean productAttributesListBean;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getSelect_state().equals("0")) {
                orderPreperBean = new OrderPreperBean();
                productInfo = new ProductInfo();
                productAttributesListBean = new ProductAttributesListBean();
                productInfo.setProductName(list.get(i).getShopname());
                productInfo.setLogo(URLConfig.BASEDOMAIN + list.get(i).getIc_path());
                productAttributesListBean.setPrice(list.get(i).getPrice());
                productAttributesListBean.setAttributeName(list.get(i).getProductAttributeName());
                orderPreperBean.setNumber((int) Double.parseDouble(list.get(i).getNumber()));
                orderPreperBean.setP(productInfo);
                orderPreperBean.setScid(list.get(i).getId());
                orderPreperBean.setAttributes(productAttributesListBean);
                orderList.add(orderPreperBean);
            }
        }
        return orderList;
    }

    private String zhuanhua(Double data) {
//        double money = Double.parseDouble(data);
        DecimalFormat df = new DecimalFormat("0.00");
        return String.format(df.format(data));
    }


    public MenuItemChangeListener menulistener;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (!(activity instanceof MenuItemChangeListener)) {
            //activity要实现此接口不然点击不跳转
        } else {
            menulistener = (MenuItemChangeListener) activity;
        }
    }

}
